package com.cy.order.service;

import com.cy.order.entity.Order;
import com.cy.order.feign.AccountClient;
import com.cy.order.feign.EasyIdClient;
import com.cy.order.feign.StorageClient;
import com.cy.order.mapper.OrderMapper;
import com.cy.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private EasyIdClient easyIdClient;

    @Autowired
    private OrderTccAction orderTccAction;

    //第一个模块开启全局事务
    @GlobalTransactional
    @Override
    public void create(Order order) {

        //生成订单id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        order.setId(orderId);

        //不再直接执行业务操作存储订单
        //而是改成调用TCC第一阶段方法，冻结订单、预留订单
        //orderMapper.create(order);
        /*
        * orderTccAction 是一个动态代理对象，用AOP添加了通知代码，
        * 在通知代码中，创建了上下文对象，并传递到被代理的目标方法中
        * */
        orderTccAction.prepare(null,order.getId(),order.getUserId(),order.getProductId(),order.getCount(),order.getMoney());

        //订单模块生成订单后，需要远程调用减少商品库存和扣减账号金额
        //调用商品库存减少商品库存
        storageClient.decrease(order.getProductId(),order.getCount());
        //调用账户金额减少账户金额
        accountClient.decrease(order.getUserId(),order.getMoney());

    }
}
